var io = require('socket.io');

var nickNames = [];

exports.initialize = function (server) {

    io = io.listen(server);

    io.sockets.on('connection', function (socket) {

        socket.on('message', function (message) {
            message = JSON.parse(message);
            if (message.type == "userMessage") {

                for (var nameObj in nickNames) {
                    if (nickNames[nameObj].key == socket.id) {
                        message.username=nickNames[nameObj].username;
                        socket.broadcast.send(JSON.stringify(message));
                        message.type = "myMessage";
                        socket.send(JSON.stringify(message));
                        return;
                    }
                }
            }
        });

        socket.on('set_name', function (data) {
            //console.log(socket);
            nickNames.push({key:socket.id,username:data.name});

            socket.emit('name_set', data);
            var message = {
                type: "serverMessage",
                message: "welcome to chat room"
            };
            socket.send(JSON.stringify(message));
        });
    });
};